from django.utils import simplejson as json
import form
from google.appengine.api import users

import common
import observer
import logging
import model
import datetime
from utils import str_is_not_blank


PLANNING_ROOM = "planning_room"

class IterationPlanningHandler(common.BaseRequestHandler):
    def _get(self):
        id = self.request.get('id')
        iteration = model.Iteration.get_by_id(int(id))
        if iteration.get_project().is_user_valid():
            self.write_out('main_planning.html', {
                          'iteration': iteration,
                          'story_form':form.StoryForm()
                          })
        else:
            self.not_allowed_error()

    def _post(self):
        id = self.request.get('id')
        iteration = model.Iteration.get_by_id(int(id))
        if iteration.get_project().is_user_valid():
            html = self.generate('iteration_planning.html', {
                          'iteration': iteration,
                          'story_form':form.StoryForm()
                          })
            self.json_response(html)
        else:
            self.not_allowed_error()
        


class PlanningEventHandler(observer.Observer):
    def _post(self):
        story_id = self.request.get('story_id')
        self.story = model.Story.get_by_id(int(story_id))
        self._post_()

    def notify_history_event(self, event):
        html = self.generate('history_event.html', {'event': event})
        response = {'event': 'add_history_event',
                    'args': {'id_event':event.key().id(),
                              'html_event': html}
                   }
        self.update(self.json_format(response))

class EditIPStoryDescriptionHandler(PlanningEventHandler):
    def _post_(self):
        description = self.request.get('description')
        self.event = model.EditDescEvent.create(self.story, self.story.description, description)
        self.story.description = description
        self.story.put()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)
    def get_response(self):
        response = {'event': 'description',
                'args': {'story_id': self.story.key().id(),
                'user': users.get_current_user().nickname(),
                'text': self.story.description}}
        return response

class AssignDeveloperHandler(PlanningEventHandler):
    def _post_(self):
        member_id = self.request.get('assigned_to')
        member = model.Member.get_by_id(int(member_id))
        self.event = model.AssignEvent.create(self.story, member.user, self.story.assigned_to, self.request.get('description'))
        self.story.assigned_to = member.user
        self.story.put()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)
        
    def get_response(self):
        response = {'event': 'assign',
                'args': {'story_id': self.story.key().id(),
                'assigned_to': self.story.assigned_to.nickname(),
                'series_hours': self.story.story_container.get_user_hours(),
                'user': users.get_current_user().nickname()}}
        return response

class EditTimeHandler(PlanningEventHandler):
    def _post_(self):
        estimated_time = self.request.get('time')
        estimated_time = float(estimated_time)
        self.event = model.TimeModifiedEvent.create(self.story, self.story.estimated_time, estimated_time, "")
        logging.info("self.event: summary: %s" %str(self.event.summary()))
        self.story.estimated_time = estimated_time
        self.story.put()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)
        
    def get_response(self):
        response = {'event': 'time',
                'args': {'story_id': self.story.key().id(),
                'estimated_time': self.story.estimated_time,
                'series_hours': self.story.story_container.get_user_hours(),
                'user': users.get_current_user().nickname()}}
        return response

class PriorityHandler(PlanningEventHandler):
    def _post_(self):
        priority = self.request.get('priority')
        self.event = model.PriorityEvent.create(self.story, self.story.priority, priority, "")
        self.story.priority = priority
        self.story.put()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)
    def get_response(self):
        response = {'event': 'priority',
                'args': {'story_id': self.story.key().id(),
                'priority': self.story.priority,
                'user': users.get_current_user().nickname()}}
        return response

class CategoryHandler(PlanningEventHandler):
    def _post_(self):
        category = self.request.get('category')
        self.event = model.CategoryEvent.create(self.story, self.story.category, category, "")
        self.story.category = category
        self.story.put()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)
        
    def get_response(self):
        response = {'event': 'category',
                'args': {'story_id': self.story.key().id(),
                'category': self.story.category,
                'user': users.get_current_user().nickname()}}
        return response

class NameHandler(PlanningEventHandler):
    def _post_(self):
        name = self.request.get('name')
        self.event = model.TaskNameEvent.create(self.story, self.story.name, name, "")
        self.story.name = name
        self.story.put()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)

    def get_response(self):
        response = {'event': 'name',
                'args': {'story_id': self.story.key().id(),
                'name': self.story.name,
                'user': users.get_current_user().nickname()}}
        return response

class CommentStoryHandler(PlanningEventHandler):
    def _post_(self):
        text = self.request.get('comment')
        comment = model.PlanningComment(story=self.story,
                                     author=users.get_current_user(),
                                     text=text)
        comment.put()

        self.update(self.get_response())
        
    def get_response(self):
        
        response = {'event': 'comment',
            'args': {'story_id': self.story.key().id(),
            'user': comment.author.nickname(),
            'comment':comment.text}}
        return response
        
class PostponeStoryHandler(observer.Observer):
    def _post(self):
        self.update(self.get_response())
        
    def get_response(self):
        story_id = self.request.get('story_id')
        story_container = self.request.get('story_container')
        story = model.Story.get_by_id(int(story_id))
        old_story_container = story.story_container
        backlog_ = model.StoryContainer.get(story_container)
        story.story_container = backlog_
        story.put()
        update = not (story.story_container.key().id() == old_story_container.key().id())
        response = {'event': 'move_story',
            'args': {'story_id': story.key().id(),
            'update': update,
            'name': story.name,
            'series_hours': old_story_container.get_user_hours(),
            'user': users.get_current_user().nickname()}}
        return json.dumps(response)



class MainHandler(common.BaseRequestHandler):
    def _post(self):
        iterations = self.get_iterations_from_param()
        if  iterations == None:
            iterations = self.get_iterations_from_cookie()
        projects = model.Project.get_projects()
        html = self.generate('index_content.html', {
                      'iterations': iterations,
                      'story_form':form.StoryForm(),
                      'current_user': users.get_current_user().nickname(),
                      'projects': projects
                      })
        self.json_response(html)

    def get_iterations_from_param(self):
        iterations = []
        id_it = self.request.get('id_it')
        user_nickname = users.get_current_user().nickname()
        if str_is_not_blank(id_it):
            iteration = model.Iteration.get_by_id(long(id_it))
            iterations.append(iteration)
            self.set_cookie('%s_IDI' %user_nickname, id_it)
            self.set_cookie('%s_IDP' %user_nickname, str(iteration.get_project().key().id()))
        else:
            id_pj = self.request.get('id_pj')
            if str_is_not_blank(id_pj):
                project = model.Project.get_project(long(id_pj))
                iterations = iterations + list(project.get_active_iterations())
                self.set_cookie('%s_IDP' %user_nickname, id_pj)
                id_it_ = str(iterations[0].key().id()) if iterations else ''
                self.set_cookie('%s_IDI' %user_nickname, id_it_)
            else:
                return None

        return iterations

    def get_iterations_from_cookie(self):
        iterations = []
        iteration = None
        user_nickname = users.get_current_user().nickname()
        try:
            idi = self.get_cookie('%s_IDI' %user_nickname)
            if str_is_not_blank(idi):
                iteration = model.Iteration.get_by_id(long(idi))
        except ValueError:
            pass


        if iteration:
            iterations.append(iteration)
            return iterations
        else:
            try:
                idp = self.get_cookie('%s_IDP' %user_nickname)
                if str_is_not_blank(idp):
                    project = model.Project.get_project(long(idp))
                else:
                    project = model.Project.get_default_project()
            except ValueError:
                project = model.Project.get_default_project()
            if project:
                iterations = iterations + list(project.get_active_iterations())

        return iterations
        
    def get_cookie(self, key):
        cookie = None
        try:
            cookie = self.request.cookies[key]
        except KeyError:
            pass
        return cookie

    def set_cookie(self, key, value): 
        today = datetime.datetime.today()
        date = datetime.date(today.year, today.month + 1, today.day)
        date_str = date.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
        self.response.headers.add_header('Set-Cookie',key +'='+ value +'; expires='+ date_str +'; path=/;')
